<template>
  <VPage class="app-container sample-list">
    <VTable
      ref="tableRef"
      v-bind="tableOptins"
      class="is--card is--line"
      @keyup="handleKeyUp"
    >
      <template #form="{ form }">
        <select-category
          v-model="form.product_category"
          :defaultProps="defaultProps"
          filterable
          placeholder="产品分类"
          @change="changeCategory"
        ></select-category>
        <VGroup>
          <el-select class="selectClass w-[100px]" v-model="form.skuRange.type">
            <el-option
              v-for="item in productCategory"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <multi-input
            v-model="form.skuRange.value"
            clearable
            placeholder="批量搜索,一行一个"
            class="w-50"
          ></multi-input>
        </VGroup>
        <multi-input
          v-model="form.sample_order_num"
          clearable
          placeholder="样品单号"
          class="w-50"
        ></multi-input>
        <multi-input
          v-model="form.purchase_order_num"
          clearable
          placeholder="采购单号"
          class="w-50"
        ></multi-input>
        <select-supplie
          class="w-40"
          v-model="form.supplier_id"
          placeholder="供应商"
        ></select-supplie>
        <VGroup>
          <el-select class="selectClass w-[100px]" v-model="form.personnelRange.type">
            <el-option
              v-for="item in testing_personnel"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <select-personnel
            v-model="form.personnelRange.value"
            :multiple="true"
            placeholder="选择"
          ></select-personnel>
        </VGroup>
        <el-select
          v-model="form.sample_type"
          collapse-tags
          placeholder="类型"
          clearable
          style="width: 182px"
        >
          <el-option
            v-for="item in options['sample.Sample']?.[0].sampleTypeText"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <VGroup>
          <el-select class="selectClass w-[100px]" v-model="form.timeRange.type">
            <el-option
              v-for="item in create_time"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-date-picker
            v-model="form.timeRange.value"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="至"
            start-placeholder="日期开始"
            end-placeholder="日期结束"
            style="max-width: 360px"
            :default-time="defaultTime()"
          />
        </VGroup>
        <el-select
          v-model="form.inspection_results"
          collapse-tags
          placeholder="检测结果"
          clearable
          style="width: 192px"
        >
          <el-option
            v-for="item in testing_result"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <teleport v-if="tabsLoad" to="#sample-tab">
          <el-tabs
            class="w-full"
            v-if="tabList.length"
            v-model="form.status"
            @tab-click="handleClick"
          >
            <el-tab-pane
              :label="item.label"
              :name="item.value"
              v-for="(item, index) in tabList"
              :key="index"
            >
              <template #label>
                {{ item.label }}(<span class="tab-count">{{ item.count }}</span
                >)
              </template>
            </el-tab-pane>
          </el-tabs>
        </teleport>
      </template>
      <template #toolbar_btns>
        <div id="sample-tab" class="w-full" v-dom-load="() => (tabsLoad = true)"></div>
        <VButton
          auth="/goods/task/sample-list/add"
          type="primary"
          icon="Plus"
          @click="addSampleFun('add')"
          >新增样品单
        </VButton>
        <VButton
          auth="/goods/task/sample-list/addPurchase"
          @click="addPurchase"
          icon="Document"
          >生成采购单</VButton
        >
        <VButton auth="/goods/task/sample-list/sampleArrival" @click="sampleArrivalFun"
          >确认样品到货</VButton
        >
        <VButton auth="/goods/task/sample-list/createPicture" @click="imageSaveFun"
          >生成图片任务</VButton
        >
        <VButton
          class="ml-auto"
          auth="/goods/task/sample-list/export"
          @click="handleExport"
        >
          <i class="dk-iconfont icon-Upload" />导出
        </VButton>
      </template>
    </VTable>
  </VPage>
  <AddSample
    ref="refAddSample"
    :options="options"
    @query="queryForm"
    @createPurchase="createPurchase"
  />
  <uploadPictures ref="uploadPictureRef" :options="options" @query="queryForm" />
  <VLog ref="logRef" class="dialogPublic" :api="queryLogList" options="sampleId"></VLog>
  <purchaseOrder ref="purchaseOrderRef"></purchaseOrder>
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
</template>
<script setup name="TaskSample-list" lang="jsx">
import {
  queryLogList,
  sampleList,
  sampleArrival,
  cancelSample,
  getSampleStatistics,
  revocationStatus,
} from "./api";
import { getOptions } from "@/api/index.js";

import SelectCategory from "@/components/SelectCategory";
import AddSample from "./components/addSample";
import uploadPictures from "./components/uploadPictures";
import VLog from "@/components/VLog";
import SelectSupplie from "@/components/SelectSupplie";
import ProductList from "./components/ProductList/index.vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";
import { nextTick, provide, watch } from "vue";
import TKTableUtils from "../../../utils/TKTableUtils";
import { deepClone } from "../../../utils";
import purchaseOrder from "./components/purchaseOrder.vue";
import { navTo } from "@/utils/navTo.js";
import {
  productCategory,
  testing_personnel,
  create_time,
  testing_result,
} from "./data.js";
import DerivedCenter from "@/components/DerivedCenter";

const store = useUserStore();
let router = useRouter();
let route = useRoute();
const tabsLoad = ref(false);

const defaultProps = {
  children: "son",
  label: "name",
  value: "id",
  checkStrictly: false,
  multiple: true,
};

const activeName = ref("");
const data = reactive({
  tabList: [
    {
      label: "全部",
      value: "",
      count: 0,
    },
    {
      label: "待收货",
      value: 0,
      count: 0,
    },
    {
      label: "待检测",
      value: 1,
      count: 0,
    },
    {
      label: "检测完成",
      value: 2,
      count: 0,
    },
    {
      label: "取消",
      value: 3,
      count: 0,
    },
  ],
  expandActives: [],
});
const { tabList, expandActives } = toRefs(data);

const tableOptins = reactive({
  rowConfig: { height: "auto", isHover: true },
  expandConfig: { reserve: true },
  scrollY: { enabled: false },
  showHeaderOverflow: false,
  showOverflow: false,
  formConfig: {
    save: "sample-list",
    remove: "sample-list",
    data: {
      skuRange: { type: "goods_sku", value: "", range: false },
      languageRange: { type: "sku_cn_title", value: [], range: true },
      timeRange: { type: "create_time", value: [], range: true },
      personnelRange: { type: "create_user_id", value: "" },
      status: "",
    },
  },
  columns: [
    { type: "checkbox", width: "40" },
    {
      field: "name",
      title: "单据信息",
      width: "220",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="flex flex-wrap">
                <span
                  class={[`statusColor${row.status}`]}
                  style=" font-size: 10px;padding-left: 4px;;padding-right: 4px;"
                >
                  {row.status_text}
                </span>
                <VText
                  type="button"
                  value={row.sample_order_num}
                  copy={true}
                  onClick={() => addSampleFun("view", row.id)}
                ></VText>
              </div>
              <div>
                <span style="font-size: 10px">￥</span>
                <div style="font-size: 14px; display: inline-flex">
                  {row.total_amount}&nbsp;&nbsp;
                </div>
                <span style="font-size: 10px">商品￥{row.total_amount}+运费</span>
              </div>
              <div style="font-size: 10px;">
                ￥{row.freight}+其他￥{row.other_fee}
              </div>
              <div style="font-size: 14px">
                <div>{row.sample_type_text}</div>
                <div>{row.supplier_id_text}</div>
              </div>
            </div>
          );
        },
      },
    },
    {
      field: "product-name",
      title: "产品信息",
      width: "400",
      slots: {
        default: ({ row, rowIndex, level }) => {
          if (row.product_list.length) {
            return <ProductList list={row.product_list} />;
          } else {
            return <div>暂无产品信息</div>;
          }
        },
      },
    },
    {
      field: "product-purchase_order_num",
      title: "采购信息",
      width: "240",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="flex">
                <span class="w-[100px]">采购单号:</span>
                {row.purchase_order_num ? (
                  <vText
                    type="button"
                    value={row.purchase_order_num}
                    copy={true}
                    onClick={() => handleNavToPurchase(row)}
                  ></vText>
                ) : (
                  "--"
                )}
              </div>
              <div>
                采购单状态:{row.supplier?.audit_status_name}{" "}
                {row.supplier?.purchase_status_name && (
                  <span>({row.supplier?.purchase_status_name})</span>
                )}
              </div>
            </div>
          );
        },
      },
    },
    {
      field: "product-info",
      title: "物流信息",
      width: "240",
      slots: {
        default: ({ row, level }) => {
          return (
            <div style="font-size: 14px">
              <div className="truncate">
                <span>物流单号：</span>
                {row.tracking_nums.length ? (
                  <span
                    class="base-text-color cursor-pointer"
                    onClick={() => handleNavToExpressage(row)}
                  >
                    {row.tracking_nums[0].cogistics_tracking_number}
                  </span>
                ) : (
                  "--"
                )}
              </div>
              <div>
                <span>目的仓库</span>
                <span style="margin-left: 10px">{row.warehouse_id_text}</span>
              </div>
              {row.tracking_nums.length > 1 && (
                <div
                  class="base-text-color cursor-pointer"
                  onClick={() => addSampleFun("view", row.id)}
                >
                  查看更多
                </div>
              )}
            </div>
          );
        },
      },
    },
    {
      field: "product-type",
      title: "样品费用",
      width: "240",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>产品金额:{row.total_goods_cost || "-"}</div>
              <div>运费:{row.freight || "-"}</div>
              <div>总金额:{row.total_amount || "-"}</div>
            </div>
          );
        },
      },
    },
    {
      field: "sales",
      title: "样品检测结果",
      width: "180",
      slots: {
        default: ({ row }) => {
          return (
            <div class="flex items-center">
              {row.inspection_results == 0 ? (
                <svg-icon class="text-yellow-400" icon-class="state_wait_line"></svg-icon>
              ) : row.inspection_results == 1 ? (
                <svg-icon
                  class="text-green-500"
                  icon-class="state_finish_cover1"
                ></svg-icon>
              ) : row.inspection_results == 2 ? (
                <svg-icon icon-class="Warning"></svg-icon>
              ) : (
                <svg-icon icon-class="Warning"></svg-icon>
              )}
              <span class="ml-1" style="font-size: 14px">
                {row.inspection_results_text}
              </span>
              &nbsp;
              <span
                style="font-size: 10px; cursor: pointer"
                class="base-text-color"
                onClick={() => checkFun(row)}
              >
                查看
              </span>
            </div>
          );
        },
      },
    },
    {
      field: "operator",
      title: "人员",
      width: "190",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="text-xs pt-1">
                建单：
                <span class="text-xs">{row.create_user_id_text}</span>
              </div>
              <div class="text-xs pt-1">
                采购：<span class="text-xs">{row.purchaser_id_text}</span>
              </div>
              <div class="text-xs pt-1">
                检测：
                <span class="text-xs">{row.testing_personnel_id_text}</span>
              </div>
              <div class="text-xs pt-1">
                修改：
                <span class="text-xs">{row.update_user_id_text}</span>
              </div>
            </div>
          );
        },
      },
    },
    {
      field: "operator-time",
      title: "时间",
      width: "190",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="text-xs pt-1">
                建单：<span class="text-xs">{row.create_time}</span>
              </div>
              <div class="text-xs pt-1">
                到货：
                <span class="text-xs">{row.expected_delivery_time || "--"}</span>
              </div>
              <div class="text-xs pt-1">
                修改：<span class="text-xs">{row.update_time}</span>
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "操作",
      width: "110",
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return (
            <div class="table-option">
              {row.status == 0 &&
                (!row.supplier?.audit_status || row.supplier?.audit_status == 6) && (
                  <div>
                    <VButton
                      auth="/goods/task/sample-list/cancel"
                      type="primary"
                      link
                      onClick={() => handleCancel(row)}
                    >
                      取消
                    </VButton>
                  </div>
                )}
              {row.status == 0 &&
                (!row.supplier?.audit_status || row.supplier?.audit_status == 6) && (
                  <div>
                    <VButton
                      auth="/goods/task/sample-list/edit"
                      type="primary"
                      link
                      onClick={() => addSampleFun("edit", row.id)}
                    >
                      编辑
                    </VButton>
                  </div>
                )}

              {row.status == 1 && (
                <div>
                  <VButton
                    auth="/goods/task/sample-list/edit"
                    type="primary"
                    link
                    onClick={() => handleRevocation(row.id)}
                  >
                    撤回
                  </VButton>
                </div>
              )}
              <div>
                <el-button type="primary" link onClick={() => viewLog(row.id)}>
                  {" "}
                  日志
                </el-button>
              </div>
              {![0, 3].includes(row.status) && (
                <div>
                  <VButton
                    auth="/goods/task/sample-list/uploadResult"
                    type="primary"
                    link
                    onClick={() => uploadPictureFun([row])}
                  >
                    上传检测结果
                  </VButton>
                </div>
              )}
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    seq: true,
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: async ({ page, form }) => {
        const dtd = {
          ...form,
          ...page,
        };
        const res = await sampleList(dtd);
        // getCount(res.data);
        getCount(form);

        // const totalItem = res.data.status.find((i) => i.status === activeName.value);

        return new Promise(function (resolve) {
          // 页码变更，vxetable会重新计算fixed的高度，所以这里要执行高度覆盖
          setTimeout(() => {
            expandFixedRow();
          });
          resolve({
            data: res.data,
            total: res.total,
          });
        });
      },
    },
  },
});

// const getCount = (countList) => {
//   tabList.value = tabList.value.map((i) => {
//     countList.filter((j) => {
//       if (i.value === j.status) {
//         i.count = j.count;
//       }
//     });
//     return i;
//   });
// };

const getCount = async (form) => {
  try {
    const res = await getSampleStatistics({
      ...form,
    });
    tabList.value = tabList.value.map((i) => {
      res.data.filter((j) => {
        if (i.value === j.status) {
          i.count = j.count;
        }
      });
      return i;
    });
  } catch (e) {
    throw Error(e);
  }
};

const clearExpandActives = () => {
  expandActives.value.length = 0;
};

const queryForm = () => {
  clearExpandActives();
  nextTick(() => {
    tableRef.value.query();
  });
};

const resetForm = () => {
  clearExpandActives();
  tableRef.value.resetAndQuery();
};

const handleClick = (res) => {
  const form = tableRef.value.getForm();
  tableRef.value.setForm({ ...form });
  queryForm();
};

const refAddSample = ref();
// 新增样品单
const addSampleFun = (type, id) => {
  nextTick(() => {
    refAddSample.value.open(type, id);
  });
};

const createPurchase = (id) => {
  purchaseOrderRef.value.open(id);
};

const purchaseOrderRef = ref();
// 生成采购单
const addPurchase = () => {
  const records = getSelectRow();
  if (records.length === 0) {
    return ElMessage({
      message: "请先勾选",
      type: "warning",
    });
  }
  const first_warehouse_id = records[0].warehouse_id;
  const first_supplier_id = records[0].supplier_id;

  const is_same = records.every((i) => {
    return first_warehouse_id === i.warehouse_id && first_supplier_id === i.supplier_id;
  });
  if (!is_same) {
    ElMessage.error("多个样品单生成同一个采购单，供应商、目的仓必须一致，请确认后操作");
    return;
  }

  const is_cancel = records.every((i) => {
    return i.status == 3;
  });

  if (is_cancel) {
    ElMessage.error("样品单状态=取消,不支持创建采购单");
    return;
  }
  const ids = records.map((i) => {
    return i.id;
  });
  purchaseOrderRef.value.open(ids.join(","));
};
// 确认样品到货
const sampleArrivalFun = () => {
  const records = getSelectRow().map((i) => i.id);
  if (records.length === 0) {
    return ElMessage({
      message: "请先勾选",
      type: "warning",
    });
  }
  sampleArrival({ sampleIds: records }).then((res) => {
    ElMessage.success(res.message);
    queryForm();
  });
};

// 生成图片任务
const imageSaveFun = () => {
  const records = getSelectRow();
  if (records.length === 0) {
    return ElMessage({
      message: "请先勾选",
      type: "warning",
    });
  }
  if (records[0].product_list.length == 0) {
    return ElMessage({
      message: "暂无产品信息,请重新选择",
      type: "error",
    });
  }
  const spu = records[0].product_list[0].goods_spu;
  const create_user_id = records[0].create_user_id;
  store.createPictureSpu({
    spu,
    create_user_id,
  });
  router.push({ path: "/task/picture" });
};

const uploadPictureRef = ref();

// 取消
const handleCancel = async (row) => {
  try {
    const res = await cancelSample({
      sampleIds: row.id,
    });
    ElMessage({
      message: res.message,
      type: "success",
    });
    queryForm();
  } catch (e) {
    throw Error(e);
  }
};

// 上传检测结果
const uploadPictureFun = (row, choice) => {
  if (choice) {
    const records = getSelectRow();
    let verifyRow = true;
    if (records.length === 0) {
      return ElMessage({
        message: "请先勾选",
        type: "error",
      });
    }
    if (records.length > 1) {
      return ElMessage({
        message: "一次只能上传一个",
        type: "error",
      });
    }
    for (let item of records) {
      if (![0, 1, 2].includes(item.status)) {
        verifyRow = false;
        return ElMessage({
          message: "只有待检测、检测完成才能上传检测结果",
          type: "error",
        });
      }
    }
    row.push(records[0]);
  }
  let { product_list } = row[0];
  if (!product_list) {
    // 兜底
    product_list = [];
  }
  nextTick(() => {
    uploadPictureRef.value.open(
      {
        sampleOrderNum: row[0].sample_order_num,
        spu: product_list.length ? product_list[0].goods_spu : "",
        sample_id: row[0].id ? row[0].id : "",
        goods_sku: product_list.length ? product_list[0].goods_sku : "",
        product_list,
        is_notify_operation: row[0].operation_user_ids ? 1 : 0,
      },
      "add"
    );
  });
};

const checkFun = (row) => {
  nextTick(() => {
    uploadPictureRef.value.open(
      {
        sampleOrderNum: row.sample_order_num,
        spu: row.product_list.length ? row.product_list[0].goods_spu : "",
        sample_id: row.id ? row.id : "",
        goods_sku: row.product_list.length ? row.product_list[0].goods_sku : "",
        product_list: row.product_list,
      },
      "view"
    );
  });
};

const tableRef = ref();
//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords();
};

const expandFixedRow = (rowIndex, visible) => {
  const beforeExpandActives = deepClone(expandActives.value);
  let needSplice;
  if (rowIndex || rowIndex === 0) {
    const _findIndex = beforeExpandActives.findIndex((v) => v === rowIndex);
    if (visible && _findIndex > -1) {
      needSplice = _findIndex;
    } else {
      beforeExpandActives.push(rowIndex);
    }
  }
  nextTick(() => {
    TKTableUtils.expandFixedRow(beforeExpandActives);
    if (typeof needSplice === "number" && needSplice > -1) {
      beforeExpandActives.splice(needSplice, 1);
    }
    expandActives.value = beforeExpandActives;
  });
};

//查看日志
const logRef = ref();
const viewLog = (id) => {
  logRef.value.open(id);
};

const options = ref({});

// 下拉数据
const fetchOption = () => {
  getOptions({ name: ["sample.SampleSku", "sample.Sample"] }).then((res) => {
    options.value = res.data;
  });
};

onMounted(() => {
  if (store.sample_sku_ids) {
    nextTick(() => {
      addSampleFun("add", store.sample_sku_ids);
      store.createSample("");
    });
  }
  fetchOption();
});

watch(
  () => route.query,
  (newVal, oldVal) => {
    console.log("store.sample_sku_ids");
    console.log(store.sample_sku_ids);

    if (store.sample_sku_ids) {
      nextTick(() => {
        addSampleFun("add", store.sample_sku_ids);
        store.createSample("");
      });
    }
  }
);

watch(
  () => activeName.value,
  (nValue) => {
    tableRef?.value.query({ status: nValue });
  }
);

// 选择品牌类型
const changeCategory = (val) => {
  if (val && val.length) {
    const lastLevelIDs = val.map((categoryPath) => categoryPath[categoryPath.length - 1]);
    const form = tableRef.value.getForm();
    setForm({ ...form, spu_category: lastLevelIDs });
  } else {
    const form = tableRef.value.getForm();
    setForm({ ...form, spu_category: 0 });
  }
};

const setForm = (val) => {
  nextTick(() => {
    tableRef.value.setForm(val);
  });
};

const handleKeyUp = (event) => {
  if (event.keyCode === 13 || event.key === "Enter") {
    queryForm();
    event.stopPropagation();
  }
};

// 跳转到快递100
const handleNavToExpressage = (val) => {
  window.open("https://www.kuaidi100.com/", "_blank");
};

const purchase_url = new Map([
  [1, "/purchase/manage/process"], // 订单状态=待提交
  [2, "/purchase/manage/audit"], // 订单状态=待审核、审核中
  [3, "/purchase/manage/purchase"], // 订单状态=审核完成
  [4, "/purchase/manage/purchase"], // 订单状态=已作废
]);

// 跳转到采购
const handleNavToPurchase = (row) => {
  const path = purchase_url.get(row.supplier?.audit_status);

  if ((window.BTN_AUTH || []).includes(path)) {
    ElMessage.error("暂无采购单管理页面权限");
    return;
  }
  sessionStorage.setItem(
    "_table_form",
    JSON.stringify({
      tableForm: { input: { type: "purchase_no", value: row.purchase_order_num } },
    })
  );
  navTo(path, "push");
};

const DerivedCenterRef = ref();

const handleExport = () => {
  const records = getSelectRow().map((i) => {
    return i.sample_order_num;
  });

  const uniqueArray = [...new Set(records)];

  let condition = {};
  if (uniqueArray.length) {
    condition.sample_order_num = uniqueArray;
  } else {
    condition = tableRef.value.getQueryForm();
  }
  DerivedCenterRef.value.open({
    tag_name: "goods_sample",
    condition,
  });
};

// 撤回
const handleRevocation = (id) => {
  ElMessageBox.confirm("撤回后状态从待检测，撤回到待收货, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "btnFalses",
  }).then(async () => {
    try {
      const res = await revocationStatus({ id });
      ElMessage.success(res.message);
      queryForm();
    } catch (e) {
      console.error(e.message);
    }
  });
};
</script>
<style>
.statusColor0 {
  color: #faad14;
  background: rgba(250, 173, 20, 0.2);
}
.statusColor1 {
  color: #3366f1;
  background: rgba(51, 102, 241, 0.1);
}
.statusColor2 {
  color: #00ac76;
  background: rgba(0, 172, 118, 0.2);
}
.statusColor3 {
  color: #6c7283;
  background-color: rgba(108, 114, 131, 0.2);
}
</style>
<style lang="scss" scoped>
.selectClass {
  &:deep(.el-select__wrapper) {
    background-color: var(--base-small-bg-color) !important;
  }
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}

.sample-list {
  .el-tabs__item.is-active {
    color: var(--el-color-primary);

    .tab-count {
      color: var(--el-color-primary) !important;
    }
  }
}

:deep(.vxe-toolbar) {
  padding-top: 8px;
}
</style>
